<div class="mdui-toolbar">
    <h1 class="mdui-typo-title">分区配置管理</h1>
    <div class="mdui-toolbar-spacer"></div>
    <button class="mdui-btn mdui-btn-icon" id="add-partition" mdui-tooltip="{content: '添加分区'}">
        <i class="mdui-icon material-icons">add</i>
    </button>
    <button class="mdui-btn mdui-btn-icon" id="refresh-tree" mdui-tooltip="{content: '刷新'}">
        <i class="mdui-icon material-icons">refresh</i>
    </button>
</div>

<div class="mdui-container-fluid" style="padding-top: 10px;">
    <div class="mdui-row">
        <!-- 左侧树形结构 -->
        <div class="mdui-col-xs-12 mdui-col-md-4">
            <div class="mdui-card">
                <div class="mdui-card-header">
                    <div class="mdui-card-header-title">分区树形结构</div>
                </div>
                <div class="mdui-card-content">
                    <div id="partition-tree" class="ds-tree-view"></div>
                    <div id="tree-loading" class="mdui-center mdui-hidden">
                        <div class="mdui-spinner mdui-spinner-color-theme"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 右侧编辑面板 -->
        <div class="mdui-col-xs-12 mdui-col-md-8">
            <div class="mdui-card" id="partition-detail-panel">
                <div class="mdui-card-header">
                    <div class="mdui-card-header-title">分区详情</div>
                </div>
                <div class="mdui-card-content">
                    <div id="no-selection" class="mdui-center" style="padding: 50px 0;">
                        <i class="mdui-icon material-icons mdui-text-color-grey-400" style="font-size: 64px;">folder</i>
                        <p class="mdui-text-color-grey-500 mdui-m-t-2">请从左侧选择一个分区进行编辑</p>
                    </div>
                    
                    <div id="partition-form" class="mdui-hidden">
                        <input type="hidden" id="partition-id" value="0">
                        
                        <div class="mdui-textfield mdui-textfield-floating-label">
                            <label class="mdui-textfield-label">分区名称</label>
                            <input class="mdui-textfield-input" type="text" id="partition-name" required />
                            <div class="mdui-textfield-error">分区名称不能为空</div>
                        </div>
                        
                        <div class="mdui-textfield mdui-textfield-floating-label">
                            <label class="mdui-textfield-label">分区图标</label>
                            <input class="mdui-textfield-input" type="text" id="partition-icon" required />
                            <div class="mdui-textfield-error">图标不能为空</div>
                            <div class="mdui-textfield-helper">请输入Material Icons图标名称，如: folder, category</div>
                        </div>
                        
                        <div class="mdui-textfield mdui-textfield-floating-label">
                            <label class="mdui-textfield-label">分区颜色</label>
                            <input class="mdui-textfield-input" type="color" id="partition-color" required />
                            <div class="mdui-textfield-error">颜色不能为空</div>
                        </div>
                        
                        <div class="mdui-textfield mdui-textfield-floating-label">
                            <label class="mdui-textfield-label">排序值</label>
                            <input class="mdui-textfield-input" type="number" id="partition-sort" min="0" value="0" required />
                            <div class="mdui-textfield-error">排序值不能为空</div>
                        </div>
                        
                        <div class="mdui-textfield mdui-textfield-floating-label">
                            <label class="mdui-textfield-label">父分区</label>
                            <select class="mdui-textfield-input" id="partition-father" mdui-select>
                                <option value="0">无父分区(根分区)</option>
                            </select>
                        </div>
                        
                        <div class="mdui-divider mdui-m-y-4"></div>
                        
                        <h3 class="mdui-typo-title">用户组访问权限</h3>
                        <div id="group-permissions" class="mdui-m-t-2">
                            <!-- 权限列表将在这里动态生成 -->
                            <div id="group-permissions-loading" class="mdui-center">
                                <div class="mdui-spinner mdui-spinner-color-theme"></div>
                            </div>
                        </div>
                        
                        <div class="mdui-divider mdui-m-y-4"></div>
                        
                        <div class="mdui-float-right">
                            <button class="mdui-btn mdui-btn-default mdui-m-r-2" id="delete-partition">删除分区</button>
                            <button class="mdui-btn mdui-btn-primary" id="save-partition">保存配置</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .ds-tree-view {
        max-height: 500px;
        overflow-y: auto;
        padding: 10px 0;
    }
    
    .ds-tree-node {
        padding: 6px 0 6px 20px;
        cursor: pointer;
        position: relative;
        user-select: none;
    }
    
    .ds-tree-node:hover {
        background-color: rgba(0, 0, 0, 0.05);
    }
    
    .ds-tree-node.active {
        background-color: rgba(0, 0, 0, 0.1);
        color: #009688;
    }
    
    .ds-tree-node-icon {
        margin-right: 8px;
        vertical-align: middle;
    }
    
    .ds-tree-node-expand {
        position: absolute;
        left: 5px;
        top: 8px;
        width: 12px;
        height: 12px;
        cursor: pointer;
        text-align: center;
        line-height: 12px;
        font-size: 10px;
    }
    
    .group-permission-item {
        padding: 10px 0;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .group-permission-item:last-child {
        border-bottom: none;
    }
</style>

<script>
    !function() {
        var $ = mdui.$;
        var currentPartition = null;
        var partitionTree = [];
        var userGroups = [];
        var saving = false;
        
        // 初始化页面
        function init() {
            // 绑定事件
            $('#add-partition').on('click', showAddPartitionDialog);
            $('#refresh-tree').on('click', loadPartitionTree);
            $('#save-partition').on('click', savePartition);
            $('#delete-partition').on('click', showDeleteConfirmDialog);
            
            // 加载分区树
            loadPartitionTree();
            // 加载用户组
            loadUserGroups();
        }
        
        // 加载分区树
        function loadPartitionTree() {
            $('#tree-loading').removeClass('mdui-hidden');
            $('#partition-tree').empty();
            
            $.ajax({
                url: './api/get_partition_list',
                dataType: 'json',
                success: function(res) {
                    if (res.code == 200) {
                        partitionTree = res.data;
                        renderPartitionTree(partitionTree);
                        renderParentPartitionSelect(partitionTree);
                    } else {
                        mdui.snackbar(res.msg || '加载分区树失败');
                    }
                },
                error: function() {
                    mdui.snackbar('网络错误，请重试');
                },
                complete: function() {
                    $('#tree-loading').addClass('mdui-hidden');
                }
            });
        }
        
        // 渲染分区树
        function renderPartitionTree(partitions) {
            // 将分区数据转换为树状结构
            const treeData = buildTree(partitions);
            
            // 递归渲染树
            function renderNode(node, level = 0, parentEl = null) {
                const nodeEl = $('<div class="ds-tree-node" data-id="' + node.id + '"></div>');
                
                // 添加缩进
                nodeEl.css('padding-left', (level * 20 + 20) + 'px');
                
                // 添加展开/折叠图标
                if (node.children && node.children.length > 0) {
                    const expandIcon = $('<span class="ds-tree-node-expand">+</span>');
                    nodeEl.prepend(expandIcon);
                    
                    expandIcon.on('click', function(e) {
                        e.stopPropagation();
                        const isExpanded = $(this).text() === '-';
                        $(this).text(isExpanded ? '+' : '-');
                        
                        // 显示/隐藏子节点
                        const childrenContainer = $(this).siblings('.ds-tree-children');
                        if (isExpanded) {
                            childrenContainer.hide();
                        } else {
                            childrenContainer.show();
                        }
                    });
                }
                
                // 添加节点内容
                const nodeContent = $('<span><i class="mdui-icon material-icons ds-tree-node-icon" style="color: ' + node.color + '">' + node.icon + '</i>' + node.name + '</span>');
                nodeEl.append(nodeContent);
                
                // 添加点击事件
                nodeEl.on('click', function() {
                    selectPartition(node);
                });
                
                // 添加到父元素
                if (parentEl) {
                    parentEl.append(nodeEl);
                } else {
                    $('#partition-tree').append(nodeEl);
                }
                
                // 渲染子节点
                if (node.children && node.children.length > 0) {
                    const childrenContainer = $('<div class="ds-tree-children"></div>');
                    nodeEl.append(childrenContainer);
                    
                    node.children.forEach(child => {
                        renderNode(child, level + 1, childrenContainer);
                    });
                }
            }
            
            // 渲染根节点
            treeData.forEach(rootNode => {
                renderNode(rootNode);
            });
        }
        
        // 将扁平数组转换为树状结构
        function buildTree(partitions) {
            const idMap = {};
            const roots = [];
            
            // 创建ID到节点的映射
            partitions.forEach(partition => {
                idMap[partition.id] = {
                    ...partition,
                    children: []
                };
            });
            
            // 构建树
            partitions.forEach(partition => {
                const node = idMap[partition.id];
                
                if (partition.father_id === 0 || !idMap[partition.father_id]) {
                    // 根节点
                    roots.push(node);
                } else {
                    // 子节点
                    idMap[partition.father_id].children.push(node);
                }
            });
            
            // 按排序值排序
            function sortBySortValue(arr) {
                return arr.sort((a, b) => (a.sort || 0) - (b.sort || 0));
            }
            
            // 递归排序所有层级
            function sortTree(node) {
                if (node.children && node.children.length > 0) {
                    node.children = sortBySortValue(node.children);
                    node.children.forEach(child => sortTree(child));
                }
            }
            
            // 对根节点排序
            const sortedRoots = sortBySortValue(roots);
            // 递归排序子节点
            sortedRoots.forEach(node => sortTree(node));
            
            return sortedRoots;
        }
        
        // 渲染父分区选择框
        function renderParentPartitionSelect(partitions) {
            const selectEl = $('#partition-father');
            selectEl.empty();
            selectEl.append('<option value="0">无父分区(根分区)</option>');
            
            // 构建树状结构
            const treeData = buildTree(partitions);
            
            // 递归添加选项
            function addOptions(node, level = 0) {
                const indent = ' '.repeat(level * 2);
                selectEl.append('<option value="' + node.id + '">' + indent + node.name + '</option>');
                
                if (node.children && node.children.length > 0) {
                    node.children.forEach(child => {
                        addOptions(child, level + 1);
                    });
                }
            }
            
            // 添加所有选项
            treeData.forEach(node => {
                addOptions(node);
            });
            
            // 更新select组件
            window.parent.mdui.mutation();
        }
        
        // 加载用户组
        function loadUserGroups() {
            // 这里应该从API加载用户组数据
            // 由于没有现成的API，暂时使用模拟数据
            userGroups = [
                {id: 1, name: '管理员组'},
                {id: 2, name: '教师组'},
                {id: 3, name: '学生组'}
            ];
        }
        
        // 选择分区
        function selectPartition(partition) {
            currentPartition = partition;
            
            // 更新选中状态
            $('.ds-tree-node').removeClass('active');
            $(`[data-id="${partition.id}"]`).addClass('active');
            
            // 显示表单
            $('#no-selection').addClass('mdui-hidden');
            $('#partition-form').removeClass('mdui-hidden');
            
            // 填充表单
            $('#partition-id').val(partition.id || 0);
            $('#partition-name').val(partition.name || '');
            $('#partition-icon').val(partition.icon || 'folder');
            $('#partition-color').val(partition.color || '#009688');
            $('#partition-sort').val(partition.sort || 0);
            $('#partition-father').val(partition.father_id || 0);
            
            // 加载用户组权限
            loadGroupPermissions(partition.id);
            
            // 更新表单组件
            window.parent.mdui.updateTextFields();
        }
        
        // 加载用户组权限
        function loadGroupPermissions(partitionId) {
            const container = $('#group-permissions');
            const loadingEl = $('#group-permissions-loading');
            
            container.empty().append(loadingEl);
            loadingEl.removeClass('mdui-hidden');
            
            // 从API加载权限数据
            $.ajax({
                url: './api/get_partition_permissions',
                method: 'GET',
                data: {
                    partition_id: partitionId
                },
                dataType: 'json',
                success: function(res) {
                    loadingEl.addClass('mdui-hidden');
                    
                    // 创建一个包含所有用户组权限状态的对象
                    const permissions = {};
                    if (res.code == 200 && res.data) {
                        res.data.forEach(permission => {
                            permissions[permission.group_id] = true;
                        });
                    }
                    
                    userGroups.forEach(group => {
                        const isChecked = permissions[group.id] ? 'checked' : '';
                        const item = $(`<div class="group-permission-item">
                            <div class="mdui-row">
                                <div class="mdui-col-xs-6">
                                    <label class="mdui-checkbox">
                                        <input type="checkbox" class="permission-checkbox" data-group-id="${group.id}" ${isChecked}>
                                        <i class="mdui-checkbox-icon"></i>
                                        <span>${group.name}</span>
                                    </label>
                                </div>
                            </div>
                        </div>`);
                        
                        container.append(item);
                    });
                },
                error: function() {
                    loadingEl.addClass('mdui-hidden');
                    mdui.snackbar('加载权限数据失败');
                }
            });
        }
        
        // 显示添加分区对话框
        function showAddPartitionDialog() {
            const dialog = $.dialog({
                history: false,
                title: '添加新分区',
                cssClass: 'ds-loadable',
                content: `
<div class="mdui-textfield mdui-textfield-floating-label">
    <label class="mdui-textfield-label">分区名称</label>
    <input class="mdui-textfield-input" type="text" id="new-partition-name" required />
    <div class="mdui-textfield-error">分区名称不能为空</div>
</div>
<div class="mdui-textfield mdui-textfield-floating-label">
    <label class="mdui-textfield-label">分区图标</label>
    <input class="mdui-textfield-input" type="text" id="new-partition-icon" value="folder" required />
    <div class="mdui-textfield-error">图标不能为空</div>
</div>
<div class="mdui-textfield mdui-textfield-floating-label">
    <label class="mdui-textfield-label">分区颜色</label>
    <input class="mdui-textfield-input" type="color" id="new-partition-color" value="#009688" required />
    <div class="mdui-textfield-error">颜色不能为空</div>
</div>
<div class="mdui-textfield mdui-textfield-floating-label">
    <label class="mdui-textfield-label">排序值</label>
    <input class="mdui-textfield-input" type="number" id="new-partition-sort" min="0" value="0" required />
    <div class="mdui-textfield-error">排序值不能为空</div>
</div>
<div class="mdui-textfield mdui-textfield-floating-label">
    <label class="mdui-textfield-label">父分区</label>
    <select class="mdui-textfield-input" id="new-partition-father" mdui-select>
        <option value="0">无父分区(根分区)</option>
    </select>
</div>
`,
                buttons: [
                    {
                        text: '取消',
                        close: true
                    },
                    {
                        text: '添加',
                        close: false,
                        onClick: function() {
                            if (saving) return;
                            
                            const name = $('#new-partition-name').val();
                            const fatherId = parseInt($('#new-partition-father').val());
                            
                            // 验证表单
                            if (!name) {
                                return mdui.snackbar('请填写分区名称');
                            }
                            
                            // 提交数据
                            saving = true;
                            dialog.$element.find('.mdui-dialog-actions button').attr('disabled', '');
                            
                            $.ajax({
                                url: './api/save_partition',
                                method: 'POST',
                                data: {
                                    id: 0,
                                    name: name,
                                    father_id: fatherId
                                },
                                dataType: 'json',
                                success: function(res) {
                                    if (res.code == 200) {
                                        mdui.snackbar('添加成功');
                                        dialog.close();
                                        loadPartitionTree();
                                    } else {
                                        mdui.snackbar(res.msg || '添加失败');
                                    }
                                },
                                error: function() {
                                    mdui.snackbar('网络错误，请重试');
                                },
                                complete: function() {
                                    saving = false;
                                    dialog.$element.find('.mdui-dialog-actions button').removeAttr('disabled');
                                }
                            });
                        }
                    }
                ]
            });
            
            // 渲染父分区选择框
            const selectEl = $('#new-partition-father');
            renderParentPartitionSelect(partitionTree);
            

            
            // 延迟更新select组件，确保DOM已经渲染
            setTimeout(() => {
                window.parent.mdui.mutation();
            }, 100);
        }
        
        // 保存分区配置
        function savePartition() {
            if (!currentPartition || saving) return;
            
            const id = parseInt($('#partition-id').val());
            const name = $('#partition-name').val();
            const fatherId = parseInt($('#partition-father').val());
            
            // 验证表单
            if (!name) {
                return mdui.snackbar('请填写分区名称');
            }
            
            // 提交数据
            saving = true;
            $('#save-partition').attr('disabled', '').text('保存中...');
            
            $.ajax({
                url: './api/save_partition',
                method: 'POST',
                data: {
                    id: id,
                    name: name,
                    father_id: fatherId
                },
                dataType: 'json',
                success: function(res) {
                    if (res.code == 200) {
                        mdui.snackbar('保存成功');
                        loadPartitionTree();
                    } else {
                        mdui.snackbar(res.msg || '保存失败');
                    }
                },
                error: function() {
                    mdui.snackbar('网络错误，请重试');
                },
                complete: function() {
                    saving = false;
                    $('#save-partition').removeAttr('disabled').text('保存配置');
                }
            });
        }
        
        // 显示删除确认对话框
        function showDeleteConfirmDialog() {
            if (!currentPartition) return;
            $.dialog({
                history: false,
                title: '确认删除',
                content: `您确定要删除分区 "${currentPartition.name}" 吗？\n\n警告：删除分区可能会影响相关的帖子分类。`,
                buttons: [
                    {
                        text: '取消',
                        close: true
                    },
                    {
                        text: '删除',
                        close: false,
                        onClick: function(dialog) {
                            // 这里应该调用删除API
                            mdui.snackbar('删除功能尚未实现');
                            dialog.close();
                        }
                    }
                ]
            });
        }
        
        // 初始化页面
        init();
    }();
</script>